package com.example.task.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author void
 * @date 2020/6/19 17:15
 * @desc
 */
@Slf4j
@Component
public class ScheduleTask3 {

//    private List<Integer> index = Arrays.asList(8 * 1000, 3 * 1000, 6 * 1000, 2 * 1000, 2 * 1000);
    private List<Integer> index = Arrays.asList(11 * 1000, 11 * 1000, 1 * 1000, 1 * 1000, 1 * 1000, 1 * 1000);
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 下一次执行在上一次执行完后间隔3s
     * @throws Exception
     */
//    @Scheduled(fixedDelay = 3 * 1000)
    public void fixedDelay() throws Exception {
        int i = atomicInteger.get();
        if (i < 5) {
            Integer sleepTime = index.get(i);
            log.info("第{}个任务开始执行,执行时间为{}ms", i, sleepTime);
            Thread.sleep(sleepTime);
            atomicInteger.getAndIncrement();
        }
   }

    /**
     * 每次0,5,10,15...时检查下是否可以执行,不行等下一次时刻点
     * @throws Exception
     */
//    @Scheduled(cron = "0/5 * * * * ? ")
    public void cron() throws Exception {
        int i = atomicInteger.get();    
        if (i < 5) {
            Integer sleepTime = index.get(i);
            log.info("第{}个任务开始执行,执行时间为{}ms", i, sleepTime);
            Thread.sleep(sleepTime);
            atomicInteger.getAndIncrement();
        }
    }

    /**
     * 会记录前面超额时间任务的次数，次数大于0下次任务立马跟上执行，正常时间执行-1
     * @throws Exception
     */
    @Scheduled(fixedRate = 5 * 1000)
    public void fixedRate() throws Exception {
        int i = atomicInteger.get();
        if (i < 6) {
            Integer sleepTime = index.get(i);
            log.info("第{}个任务开始执行,执行时间为{}ms", i+1, sleepTime);
            Thread.sleep(sleepTime);
            atomicInteger.getAndIncrement();
        }
    }
}
